package sit.mycatalog.ejb.dao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import sit.mycatalog.jpa.Item;
import sit.mycatalog.util.AbstractDao;
import sit.mycatalog.util.ParamBinder;

/**
 * Session Bean implementation class ItemDao
 */
@Stateless
@LocalBean
public class ItemDao extends AbstractDao<Item> {

	/**
	 * Default constructor.
	 */
	public ItemDao() {
		super(Item.class);
	}

	public List<Item> findByCatid(Integer p_intCatid) throws Exception {
		List<Item> lsItem = null;

		try {
			StringBuilder sql = new StringBuilder();
			sql.append("SELECT i \n");
			sql.append("FROM Item i \n");
			sql.append("WHERE i.catid = :catid \n");
			sql.append("ORDER BY i.item");

			ParamBinder pb = new ParamBinder();
			pb.put("catid", p_intCatid);

			lsItem = findList(sql, pb);

		} catch (Exception e) {
			throw new Exception("findByCatid(): " + e.getMessage(), e);
		}

		return lsItem;
	}
	
	public List<Item> findHotItem() throws Exception {
		List<Item> lsItem = null;

		try {
			StringBuilder sql = new StringBuilder();
			sql.append("SELECT i \n");
			sql.append("FROM Item i \n");
			sql.append("WHERE i.hot = :hot \n");
			sql.append("ORDER BY i.item");

			ParamBinder pb = new ParamBinder();
			pb.put("hot", "Y");

			lsItem = findList(sql, pb);

		} catch (Exception e) {
			throw new Exception("findByCatid(): " + e.getMessage(), e);
		}

		return lsItem;
	}

	public List<Item> findItemByKeyword(String p_strKeyword) throws Exception {
		List<Item> lsItem = null;

		try {
			if ((p_strKeyword != null) && (p_strKeyword.length() > 0)) {
				StringBuilder sql = new StringBuilder();
				sql.append("SELECT i \n");
				sql.append("FROM Item i \n");
				sql.append("WHERE i.item LIKE :keyword \n");
				sql.append("OR i.description LIKE :keyword \n");
				sql.append("ORDER BY i.item");
				
				ParamBinder pb = new ParamBinder();
				pb.put("keyword", "%" + p_strKeyword.toUpperCase() + "%");

				lsItem = findList(sql, pb);
			}

		} catch (Exception e) {
			throw new Exception("findByCatid(): " + e.getMessage(), e);
		}
		
		return lsItem;
	}
	
	public List<Item> findAll() throws Exception {
		List<Item> lsItem = null;

		try {
			StringBuilder sql = new StringBuilder();
			sql.append("SELECT i \n");
			sql.append("FROM Item i \n");
			sql.append("ORDER BY i.item");

			lsItem = findList(sql);

		} catch (Exception e) {
			throw new Exception("findAll(): " + e.getMessage(), e);
		}

		return lsItem;
	}
}
